import matplotlib
matplotlib.use('Agg')
import os
from flask import Flask, render_template
from src.data_processing import data_processing
from src.process_names_mapping import generate_process_name_mapping
from matplotlib.font_manager import FontProperties
from src.core.user_persona.user_persona_board import init_user_dash
from src.core.usage.usage_board import init_usage_dash
from src.core.churn_prediction.churn_predection_board import init_churn_predection_dash
from src.core.group_portraits.group_portraits_board import init_group_portraits_board

import seaborn as sns
# 设置 seaborn 的字体
font_path = r'C:\Windows\Fonts\msyh.ttc'
myfont = FontProperties(fname=font_path)
sns.set_theme(font=myfont.get_name())

def create_app():
    server = Flask(__name__, template_folder='assets')

    init_user_dash(server)
    init_usage_dash(server)
    init_churn_predection_dash(server)
    init_group_portraits_board(server)
    
    return server

app = create_app()

@app.route('/')
def index():
    return render_template('index.html')

def init():
    behavior_dir = os.path.join('data', 'behavior')
    if not os.path.isdir(behavior_dir):
        print("请导入用户日志数据到data目录")
    
    processed_dir = os.path.join('data', 'processed')
    if not os.path.isdir(processed_dir):
        data_processing()
    
    mapping_file = os.path.join('data', 'process_names_mapping.csv')
    if not os.path.isfile(mapping_file):
        generate_process_name_mapping()

if __name__ == '__main__':
    init()
    app.run(host='127.0.0.1', port=8888)